'use strict';
var db = uniCloud.database(); // 全局数据库引用
var _ = db.command; // 数据库操作符
var $ = _.aggregate; // 聚合查询操作符

const calcFx2Reward = require('../util/calcFx2Reward');
const calcRegionalAgentReward = require('../util/calcRegionalAgentReward');
const addReward = require('../util/addReward');

module.exports = {
	/**
	 * 订单付款后的奖励逻辑
	 * @param {Object} taskInfo  任务信息
	 * @param {Object} orderInfo 订单信息
	 * @param {Object} userInfo 下单人信息
	 * @param {Object} mchInfo 商家配置信息
	 */
	run: async (data) => {
		let res = { code: 0, msg: "ok" };
		// 业务逻辑开始-----------------------------------------------------------
		let {
			taskInfo, //  任务信息
			orderInfo, // 订单信息
			userInfo, // 下单人信息
			mchInfo, // 商家配置信息
		} = data;

		let {
			order_no, // 订单号
		} = orderInfo;

		// 发放奖励（除了记录整个订单共奖励多少外，还需要记录该订单内的每个商品分别奖励多少）
		let usersRewardList = [];

		// 二级分销模式
		let fx2RewardList = await calcFx2Reward({ orderInfo, mchInfo, userInfo });
		usersRewardList = usersRewardList.concat(fx2RewardList);

		// 区域代理奖励
		let regionalAgentRewardList = await calcRegionalAgentReward({ orderInfo, mchInfo, userInfo });
		usersRewardList = usersRewardList.concat(regionalAgentRewardList);

		let payment_amount = orderInfo.amount_info.payment_amount;
		let sumUsersReward = 0;
		// 打印奖励日志
		usersRewardList.map((item, index) => {
			console.log(`用户【${item.user_id}】获得【${item.reward_name}】奖励：${item.reward_value_format} 元`);
			sumUsersReward += item.reward_value;
		});
		let express_amount = orderInfo.amount_info.express_amount; // 运费
		let goodsPaymentAmount = payment_amount - express_amount; // 去除运费
		console.log(`订单实付金额（不含运费）：${vk.pubfn.toDecimal(goodsPaymentAmount / 100, 2)} 元，共发放奖励：${vk.pubfn.toDecimal(sumUsersReward / 100, 2)} 元，奖励占比：${vk.pubfn.toDecimal(sumUsersReward / goodsPaymentAmount * 100, 6)}%`);
		console.log('usersRewardList: ', usersRewardList);

		// 发放奖励
		res = await addReward({
			taskInfo, //  任务信息
			orderInfo, // 订单信息
			userInfo, // 下单人信息
			mchInfo, // 商家配置信息
			usersRewardList, // 用户奖励列表
		});

		// 业务逻辑结束-----------------------------------------------------------
		return res;
	}
}
